import { useAppStore } from "~/store/appStore";
import { Snackbar } from "@varlet/ui";

export const BASE_URL = "https://ferret.icu/api";
// export const BASE_URL = "http://localhost:10011/api";
import axios, { type AxiosRequestConfig } from "axios";
const http = axios.create({
  baseURL: BASE_URL,
});
http.interceptors.request.use(
  (config) => {
    
    if (process.client) {
      const cookie = document.cookie;
      const fingerprint = cookie
        .split(";")
        .find((item) => item.includes("fingerprint"));
      if (fingerprint) {
        config.headers.fingerprint = fingerprint.split("=")[1];
      }
    }
    if (config.headers.fingerprint) return config;
    const AppStore = useAppStore();
    const token = AppStore.token;
    if (token) {
      config.headers.Authorization = "Berae " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
http.interceptors.response.use(
  (response) => {
    const { code, message } = response.data as ApiResponse<any>;
    if (code !== 200) {
      throw new Error(message);
    }
    return response.data;
  },
  (error) => {
    Snackbar.error(error.message);
    return Promise.reject(error);
  }
);

export interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}
export async function request<T>(config: AxiosRequestConfig) {
  return http.request<T>(config).then((res) => res.data); // 返回axios的里data数据
}
import { type UseFetchOptions } from "nuxt/app";

export function useMyFetch<T = any>(
  url: string | Ref<string>,
  options: UseFetchOptions<any> = {}
) {
  const appStore = useAppStore();
  const token = appStore.token;
  return useFetch<ApiResponse<T>>(url, {
    headers: {
      Authorization: token || "",
    },
    baseURL: BASE_URL,
    onRequest({ request, options }) {
      // 处理请求数据
    },
    onRequestError({ request, options, error }) {
      // 处理请求错误
      if (process.server) {
        Snackbar.error(`请求错误: ${error.message}`);
      }
    },
    onResponse({ request, response, options }) {
      // 处理响应数据
      const { code, data, message } = response._data as ApiResponse<T>;
      if (code !== 200 && process.server) {
        Snackbar.error(message);
      }
    },
    onResponseError({ request, response, options }) {
      // 处理响应错误
      const { status } = response;
      if (process.server) {
        Snackbar.error(`响应错误: ${status}`);
      }
    },
    ...options,
  });
}
